﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.CodeDom.Compiler;
using System.IO;
using System.CodeDom;
using DotNetDalAddin.Properties;

namespace DotNetDalAddin.CodeHelper
{
    public class BusinessCodeTable
    {
        private CodeNamespace codeNs = new CodeNamespace();
        private DotNetDal.Core.Model.Table table = new DotNetDal.Core.Model.Table();

        public BusinessCodeTable(DotNetDal.Core.Model.Table t)
        {
            table = t;

            GenerateClass();
        }

        public string GenerateCode(string nameSpace)
        {
            CodeGeneratorOptions cop = new CodeGeneratorOptions();

            cop.BracingStyle = "C";
            cop.IndentString = "    ";

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);

            ICodeGenerator cg = new Microsoft.CSharp.CSharpCodeProvider().CreateGenerator();

            cg.GenerateCodeFromNamespace(InitializeNameSpace(nameSpace), sw, cop);

            return sb.ToString();
        }

        public void GenerateClass()
        {
            CodeTypeDeclaration ctd = new CodeTypeDeclaration(table.Name);
            ctd.BaseTypes.Add(new CodeTypeReference(Settings.Default.AbstractFolderName + ".Abstract" + table.Name));
            ctd.Attributes = MemberAttributes.Abstract;
            ctd.IsPartial = true;

            codeNs.Types.Add(ctd);
        }

        private CodeNamespace InitializeNameSpace(string name)
        {
            codeNs.Imports.Add(new CodeNamespaceImport("System"));
            codeNs.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            codeNs.Name = name + "." + Settings.Default.BusinessFolderName;

            return codeNs;
        }
    }
}
